package com.liao.rent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liao.rent.dto.HouseDeatilsDto;
import com.liao.rent.dto.houseQuertDto;
import com.liao.rent.entity.House;
import com.liao.rent.entity.HouseAttr;
import com.liao.rent.entity.JsonResult;
import com.liao.rent.entity.SysUserDetails;
import com.liao.rent.mapper.HouseMapper;
import com.liao.rent.service.HouseAttrService;
import com.liao.rent.service.HouseService;
import com.liao.rent.utils.ResultTool;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

import static com.liao.rent.utils.AddressLocationUtil.getLonAndLatByAddress;

/**
 * <p>
 * 房源表 前端控制器
 * </p>
 *
 * @author liao
 * @since 2024-11-30
 */
@Slf4j
@Tag(name = "房源管理")
@RestController
@RequestMapping("/house")
public class HouseController {

    @Autowired
    HouseService houseService;

    @Autowired
    HouseAttrService houseAttrService;

    @Autowired
    HouseMapper houseMapper;

    @GetMapping("/list")
    @Operation(summary = "查询全部租期列表")
//    public JsonResult<Page<House>> listLeaseTerm(@RequestParam(required = false) houseQuertDto houseQuertDto, @RequestParam(required = false,defaultValue = "1") Integer pageNum, @RequestParam(required = false,defaultValue = "10")Integer pageSize) {

    public JsonResult<Page<House>> listLeaseTerm(houseQuertDto houseQuertDto) {

        LambdaQueryWrapper<House> houseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        log.info("查询条件：{}",houseQuertDto);
        houseLambdaQueryWrapper.like(!StringUtils.isEmpty(houseQuertDto.getTitle()), House::getTitle, houseQuertDto.getTitle());
        houseLambdaQueryWrapper.like(!StringUtils.isEmpty(houseQuertDto.getAddress()), House::getAddress, houseQuertDto.getAddress());


        //判断用户是否是房东，是则查询房东的房源
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        authorities.forEach(authority -> {
        //显示房东发布的所欲房源
            if (authority.getAuthority().equals("landlord")) {
                houseLambdaQueryWrapper.eq(House::getCreateUser, ((SysUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser().getId());
            }
            //如果是房客，则查询出在出租的所有房源
            if (authority.getAuthority().equals("regular_users")){
                houseLambdaQueryWrapper.eq(House::getStatus,"2");
            }

        });

//        Page<House> page = houseService.page(new Page<>(pageNum, pageSize),houseLambdaQueryWrapper);
        Page<House> page = houseService.page(new Page<>(houseQuertDto.getPageNum(), houseQuertDto.getPageSize()),houseLambdaQueryWrapper);

        return ResultTool.success(page);
    }



    @GetMapping("/houseDetails/{houseId}")
    @Operation(summary = "根据id查询房源详情")

    public JsonResult<HouseDeatilsDto> houseDetails(@PathVariable("houseId") Integer houseId) {
//        构造查询语句
        LambdaQueryWrapper<House> houseLambdaQueryWrapper = new LambdaQueryWrapper<House>().eq(House::getHouseId, houseId);
        House house = houseService.getOne(houseLambdaQueryWrapper);
        //        构造查询语句
        LambdaQueryWrapper<HouseAttr> houseAttrLambdaQueryWrapper = new LambdaQueryWrapper<HouseAttr>().eq(HouseAttr::getHouseId, houseId);
        HouseAttr houseAttr = houseAttrService.getOne(houseAttrLambdaQueryWrapper);
        HouseDeatilsDto houseDeatilsDto = new HouseDeatilsDto();
        houseDeatilsDto.setHouse(house);
        houseDeatilsDto.setHouseAttr(houseAttr);

        return ResultTool.success(houseDeatilsDto);

    }


    @PostMapping("/add")
    @Operation(summary = "添加房源")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('landlord')")
    public JsonResult<String> addHouse(@RequestBody HouseDeatilsDto houseDeatilsDto) {
        try {
            editOrCreateHouse(houseDeatilsDto);
            houseService.save(houseDeatilsDto.getHouse());

            houseDeatilsDto.getHouseAttr().setHouseId(houseDeatilsDto.getHouse().getHouseId());

            houseAttrService.save( houseDeatilsDto.getHouseAttr());
        }catch (Exception e){
            log.info(e.toString());
            return ResultTool.fail("添加失败");

        }

        return ResultTool.success("添加成功");
    };

//    @PostMapping("/update")
//    @Operation(summary = "修改房源")
//    public JsonResult<String> updateHouse(@RequestBody House house) {
//        houseService.updateById(house);
//        return ResultTool.success("修改成功");
//    }


    @PostMapping("/edit")
    @Operation(summary = "修改房源")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('landlord')")
    public JsonResult<String> editHouse(@RequestBody HouseDeatilsDto houseDeatilsDto) {
        try {
            editOrCreateHouse(houseDeatilsDto);
            houseService.updateById(houseDeatilsDto.getHouse());
            houseAttrService.updateById( houseDeatilsDto.getHouseAttr());
        }catch (Exception e){
            return ResultTool.fail("修改失败");
        }

        return ResultTool.success("修改成功");

    }

    @PostMapping("/updateHouseStatus/{houseId}/{status}")
    @Operation(summary = "更新房源状态")
    public JsonResult<String> updateHouseStatus(@PathVariable("houseId") Integer houseId,@PathVariable("status") Integer status) {
//        构建sql语句
        LambdaUpdateWrapper<House> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.eq(House::getHouseId,houseId).set(House::getStatus,status);

        updateWrapper.set(House::getStatus,status);

        houseService.update(updateWrapper);

        return ResultTool.success("ok");

    }

    @PostMapping("/delete/{houseId}")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('landlord')")
    @Operation(summary = "删除房源")
    public JsonResult<String> delete(@PathVariable("houseId") Integer houseId) {
        try {
            House house = houseService.getById(houseId);
            if (house.getStatus() == 3){
                return ResultTool.fail("该房源正在出租中，无法删除");
            }
            houseService.removeById(houseId);
            LambdaQueryWrapper<HouseAttr> wrapper = new LambdaQueryWrapper<>();

            wrapper.eq(HouseAttr::getHouseId,houseId);
            houseAttrService.remove(wrapper);

        }catch (Exception e){
            return ResultTool.fail("删除失败");
        }

        return ResultTool.success("ok");
    }



    /**
     * 创建或修改房源 失败则抛出异常
     * @param houseDeatilsDto
     */
    private void editOrCreateHouse(HouseDeatilsDto houseDeatilsDto) throws Exception{
        House house = houseDeatilsDto.getHouse();
        HouseAttr houseAttr = houseDeatilsDto.getHouseAttr();
        //从安全上下文中获取当前用户对象
        SysUserDetails userDetails = (SysUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            获取当前用户id设置用户id
        house.setUserId(userDetails.getUser().getId());
//            设置房源状态(未审核)
        house.setStatus(0);
//            获取经纬度设置
        String location=getLonAndLatByAddress(house.getAddress());
        house.setLongitudeLatitude(location);


    }







}
